import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../provider/comment_provider.dart';
import '../utils/api.dart';
import '../widgets/FollowButton.dart';
import '../widgets/comment_input_sheet.dart';
import '../widgets/comment_section.dart';
import '../widgets/like_button.dart';
import '../widgets/post_page_slider.dart';
import 'UserProfilePage.dart';

class PostDetailPage extends StatefulWidget {
  final String postId;

  const PostDetailPage({super.key, required this.postId});

  @override
  State<PostDetailPage> createState() => _PostDetailPageState();
}

class _PostDetailPageState extends State<PostDetailPage> {
  Map<String, dynamic>? post;

  @override
  void initState() {
    super.initState();
    _fetchPost();
  }

  Future<void> _fetchPost() async {
    try {
      final res = await Api.get(
        '/cms/post/detail',
        params: {'id': widget.postId},
      );

      if (res['code'] == 0 && res['data'] != null && res['data'] is Map) {
        setState(() {
          post = Map<String, dynamic>.from(res['data']);
        });
      } else {
        // 处理无效响应，例如跳转错误页、提示等
        debugPrint('获取帖子详情失败：${res['message'] ?? '未知错误'}');
        if (mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(SnackBar(content: Text('加载帖子失败，请稍后重试')));
          Navigator.of(context).pop(); // 返回上一页或跳转错误页
        }
      }
    } catch (e, stack) {
      debugPrint('帖子详情加载异常: $e\n$stack');
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('网络异常，请稍后重试')));
        Navigator.of(context).pop();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (post == null) {
      return const Scaffold(body: Center(child: CircularProgressIndicator()));
    }
    return ChangeNotifierProvider(
      create: (_) => CommentProvider(post!['id']),
      child: _PostDetailPageContent(post: post!),
    );
  }
}

class _PostDetailPageContent extends StatelessWidget {
  final Map<String, dynamic> post;

  const _PostDetailPageContent({required this.post});

  static const double bottomBarHeight = 56;
  static const double authorBarHeight = 56;

  @override
  Widget build(BuildContext context) {
    final images = post['images'] != null
        ? List<String>.from(jsonDecode(post['images']))
        : <String>[];

    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Column(
          children: [
            // 作者栏
            Container(
              height: authorBarHeight,
              padding: const EdgeInsets.symmetric(horizontal: 16),
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 4,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Row(
                children: [
                  GestureDetector(
                    onTap: () {
                      context.pushNamed(
                        'userProfile',
                        pathParameters: {'id': post['userId'].toString()},
                        queryParameters: {'nickname': post['nickname']},
                      );
                    },
                    child: CircleAvatar(
                      radius: 18,
                      backgroundImage: NetworkImage(
                        post['avatar'] ?? 'https://via.placeholder.com/150',
                      ),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: GestureDetector(
                      onTap: () {
                        Navigator.of(context).pushReplacement(
                          MaterialPageRoute(
                            builder: (_) => UserProfilePage(
                              userId: post['userId'].toString(),
                              nickname: post['nickname'],
                            ),
                          ),
                        );
                      },
                      child: Text(
                        post['nickname'] ?? '匿名用户',
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ),
                  FollowButton(userId: post['userId'].toString()),
                ],
              ),
            ),

            Expanded(
              child: CustomScrollView(
                slivers: [
                  SliverAppBar(
                    expandedHeight: 300,
                    pinned: true,
                    automaticallyImplyLeading: false,
                    elevation: 0,
                    backgroundColor: Colors.white,
                    iconTheme: const IconThemeData(color: Colors.black),
                    flexibleSpace: FlexibleSpaceBar(
                      collapseMode: CollapseMode.pin,
                      background: PostImageSlider(images: images),
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: Padding(
                      padding: const EdgeInsets.fromLTRB(
                        16,
                        16,
                        16,
                        bottomBarHeight + 16,
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            post['title'] ?? '',
                            style: const TextStyle(
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 12),
                          Text(
                            post['content'] ?? '',
                            style: const TextStyle(fontSize: 16),
                          ),
                          const SizedBox(height: 24),
                          const Divider(
                            height: 1,
                            thickness: 0.5,
                            color: Color(0x4D9E9E9E),
                          ),
                          const CommentSection(),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),

            // 底部评论栏
            Material(
              elevation: 8,
              color: Colors.white,
              child: SafeArea(
                top: false,
                child: Container(
                  height: bottomBarHeight,
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: Row(
                    children: [
                      LikeButton(postId: post['id'].toString()),
                      IconButton(
                        icon: const Icon(Icons.star_outline_sharp),
                        onPressed: () {},
                        padding: EdgeInsets.zero,
                        constraints: const BoxConstraints(
                          minWidth: 40,
                          minHeight: 40,
                        ),
                      ),
                      const Spacer(),
                      ElevatedButton(
                        onPressed: () => _showCommentSheet(context, post['id']),
                        style: ElevatedButton.styleFrom(
                          shape: const StadiumBorder(),
                          backgroundColor: Colors.black,
                          foregroundColor: Colors.white,
                          padding: const EdgeInsets.symmetric(
                            horizontal: 24,
                            vertical: 6,
                          ),
                          minimumSize: const Size(0, 36),
                        ),
                        child: const Text("评论"),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _showCommentSheet(BuildContext context, int postId) async {
    final provider = Provider.of<CommentProvider>(context, listen: false);

    final result = await showModalBottomSheet<bool>(
      context: context,
      isScrollControlled: true,
      builder: (_) => CommentInputSheet(postId: postId),
    );

    if (result == true && context.mounted) {
      await provider.loadComments();
    }
  }
}
